package controller.addtextServlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import dao.util.FilesCreate;
import bean.User;

import java.io.IOException;

@WebServlet("/mynote/Delete")
public class Delete extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 浏览器可能用 GET 来删除，这里统一调用 doPost
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=utf-8");
        String filename = req.getParameter("filename");
        User currentUser = null;
        if (req.getSession(false) != null) {
            currentUser = (User) req.getSession(false).getAttribute("user");
        }
        int userId = currentUser != null ? currentUser.getId() : -1;

        if (filename == null || filename.isEmpty()) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("删除失败：缺少文件名");
            return;
        }
        FilesCreate filesCreate = new FilesCreate();
        filesCreate.getMapperClass().deleteFileByName(filename, userId);
        filesCreate.commitsession();
        filesCreate.closesession();
    }
}
